<template>
  <div>
    <div class="page_title">角色管理</div>
    <FormTable
      :form-rules="formRules"
      :table-data="tableData"
      :columns="columns"
      :total="total"
      :current-page="pageIndex"
      :page-size="pageSize"
      @change-table-data="changeTableData"
      @query-table="queryTable"
    >
      <template #tableTabs>
        <div style="display: flex; justify-content: end; margin-bottom: 16px">
          <el-button type="primary" @click="edit1()">新增</el-button>
        </div>
      </template>
      <template #operator="{ slotProps }" class="table_button_list">
        <el-button link type="primary" @click="edit1(slotProps)"
          >修改</el-button
        >
        <el-popconfirm
          title="确认删除吗？"
          placement="top-start"
          @confirm="delItem(slotProps)"
        >
          <template #reference>
            <el-button link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </FormTable>
    <jsglForm
      v-model="dialogVisible"
      :data-form="dialogForm"
      v-if="dialogVisible"
      @close="dialogVisible = false"
      :is-detail="isDetail"
      @get-datas="queryTable"
    />
  </div>
</template>

<script>
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import { ElMessage } from "element-plus";
import { apiUrl } from "@/api/api";

import axios from "axios";
import FormTable from "@/components/FormTable/index.vue";
import jsglForm from "./jsglForm.vue";

export default defineComponent({
  name: "ApplicationIdentityManagement",
  components: { FormTable, jsglForm },
  setup() {
    const dataMap = reactive({
      tableData: [],
      appNameOptions: [], // 初始为空数组
      formRules: [
        {
          type: "select",
          field: "applicationId",
          title: "应用名称",
          options: [], // 初始为空数组
          props: {
            label: "label",
            value: "value",
          },
          on: {
            change: (val) => {
              // 当选择应用时触发数据请求
              if (val) {
                getDatas(val);
              }
            },
          },
        },
      ],
      searchForm: {
        applicationId: "",
      },
      columns: [
        {
          label: "序号",
          type: "index",
          width: "70px",
        },
        {
          label: "身份名称",
          prop: "name",
        },

        {
          label: "编码",
          prop: "code",
        },
        {
          label: "默认组织",
          prop: "isDefaultName",
        },
        {
          prop: "operator",
          label: "操作",
          align: "center",
          width: "120px",
        },
      ],
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      isDetail: false,
      isFabu: false,
      dialogForm: {},
      currentAppId: null, // 当前选中的应用ID
    });

    const fetchAppNames = async () => {
      try {
        const response = await axios({
          method: "post",
          url: apiUrl.baseUrl + "/wl/auth/application/getList",
          data: {},
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
            loginToken: sessionStorage.getItem("loginToken"),
          },
        });

        // 只更新应用列表，不自动选择第一个应用
        dataMap.appNameOptions =
          response.data?.data?.data?.map((item) => ({
            value: item.id,
            label: item.applicationName,
          })) || [];

        // 更新表单选择器选项
        dataMap.formRules[0].options = dataMap.appNameOptions;
      } catch (error) {
        ElMessage.error("获取应用列表失败");
        console.error("Error fetching app names:", error);
      }
    };

    const getDatas = async (appId) => {
      if (!appId) {
        // 如果没有appId，清空表格数据
        dataMap.tableData = [];
        dataMap.total = 0;
        return;
      }

      dataMap.currentAppId = appId;
      let data = {
        pageNum: dataMap.pageIndex,
        pageSize: dataMap.pageSize,
        groups: [],
        rules: [
          {
            field: "applicationId",
            data: appId,
            opType: "Equals",
          },
        ],
        orderBys: [],
      };
      try {
        const response = await axios({
          method: "post",
          url: apiUrl.baseUrl + "/wl/auth/identity/getPageList",
          data: data,
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
            loginToken: sessionStorage.getItem("loginToken"),
          },
        });

        dataMap.tableData = response.data?.data?.data?.list || [];
        dataMap.total = response.data?.data?.data?.total || 0;
        dataMap.tableData.forEach((element) => {
          if (element.isDefault === "0") {
            element.isDefaultName = "否";
          } else if (element.isDefault === "1") {
            element.isDefaultName = "是";
          }
        });
      } catch (error) {
        ElMessage.error("获取数据失败");
        console.error("Error fetching data:", error);
      }
    };

    const delItem = async (item) => {
      try {
        await axios({
          method: "get",
          url: apiUrl.baseUrl + `/auth/identity/delete?id=${item.id}`,
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
            loginToken: sessionStorage.getItem("loginToken"),
          },
        });

        ElMessage.success("删除成功");
        // 删除后重新加载当前应用的数据
        if (dataMap.currentAppId) {
          await getDatas(dataMap.currentAppId);
        }
      } catch (error) {
        ElMessage.error("删除失败");
        console.error("Error deleting item:", error);
      }
    };

    const edit1 = (items) => {
      if (items) {
        dataMap.dialogForm = { ...items };
        dataMap.isDetail = true;
      } else {
        dataMap.dialogForm = {};
        dataMap.isDetail = false;
      }
      dataMap.dialogVisible = true;
    };

    const changeTableData = (pageNum, pageSize) => {
      dataMap.pageIndex = pageNum;
      dataMap.pageSize = pageSize;
      if (dataMap.currentAppId) {
        getDatas(dataMap.currentAppId);
      }
    };

    const queryTable = (params = {}) => {
      dataMap.searchForm = { ...params };
      dataMap.pageIndex = 1;
      if (dataMap.currentAppId) {
        getDatas(dataMap.currentAppId);
      }
    };

    onMounted(() => {
      fetchAppNames();
    });

    return {
      ...toRefs(dataMap),
      edit1,
      delItem,
      changeTableData,
      queryTable,
    };
  },
});
</script>

<style lang="scss" scoped>
.page_title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}
</style>
